package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> headers = new HashMap<>();
        Map<String,String> querys = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2179819504");
        map.put("client_secret", "5ca0cb26792aabea43f1e24058fcf19b");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);


        //1、根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", headers, querys, map);
        System.out.println(response.getEntity());
        System.out.println(response.getStatusLine().getStatusCode());

        //2、处理
        if(response.getStatusLine().getStatusCode() == 200){
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道当前用户是哪个社交用户
            //1）、当前用户如果是第一次登录，就自动注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            //登陆或者注册这个社交用户
            R oauthlogin = memberFeignService.oauthlogin(socialUser);
            if(oauthlogin.getCode() == 0){
                //社交登录成功
                MemberRespVO data = oauthlogin.getData("data", new TypeReference<MemberRespVO>() {
                });
                log.info("登陆成功：用户：{}", data.toString());
                //1、
                session.setAttribute("loginUser", data);
                return "redirect:http://gulimall.com";
            }else {
                /*//社交登录失败
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", oauthlogin.getData("msg", new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors", errors);*/
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else {
            //没有获取到token --> 登录失败 页面跳转到登录页面继续登录
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

}
